package com.wanxi.chat.messagehandler.chat;


import com.wanxi.chat.codec.Invocation;
import com.wanxi.chat.dispatcher.MessageHandler;
import com.wanxi.chat.message.chat.ChatSendRequest;
import com.wanxi.chat.message.chat.ChatSendResponse;
import com.wanxi.chat.server.NettyChannelManager ;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ChatSendHandler implements MessageHandler<ChatSendRequest> {

    @Autowired
    private NettyChannelManager nettyChannelManager;

    @Override
    public void execute(Channel channel, ChatSendRequest message) {
        // 返回响应
        ChatSendResponse sendResponse = new ChatSendResponse();
        sendResponse.setMessage(message.getContent());
        sendResponse.setCode(0);
        sendResponse.setToId(message.getToId());
        channel.writeAndFlush(new Invocation(ChatSendResponse.TYPE, sendResponse));

        // 创建转发的消息，发送给指定用户
        ChatSendRequest sendToUserRequest = new ChatSendRequest();
        sendToUserRequest.setContent(message.getContent());
        sendToUserRequest.setMsgId(message.getMsgId());
        sendToUserRequest.setToId(message.getToId());
        sendToUserRequest.setFromId(message.getFromId());
        nettyChannelManager.send(message.getToId(), new Invocation(ChatSendRequest.TYPE, sendToUserRequest));
    }

    @Override
    public String getType() {
        return ChatSendRequest.TYPE;
    }

}
